from google.appengine.api import memcache

from app.web import abstract
import operator, math

MAX_ITEMS = 100

class Action(abstract.Action):
    
    def get(self):
        
        callback = self.param("callback")
        
        mc_key = "tc/0"
        
        data = memcache.get(mc_key)
        
        if not data:
            tags = abstract.models.tag.list(MAX_ITEMS)
                
            data = self.makeCloud(40, tags)
            
            memcache.set(mc_key, data, 600)
        
        self.jsonp(sorted(data, key=operator.itemgetter("name")), callback)
        
        
    def makeCloud(self, steps, input):
    
            temp, newThresholds, results = [], [], []
            
            for item in input:
                temp.append(item.count)
                
            maxWeight = float(max(temp))
            minWeight = float(min(temp))
            
            newDelta = (maxWeight - minWeight) / float(steps)
            
            for i in range(steps + 1):
                newThresholds.append((100 * math.log((minWeight + i * newDelta) + 2), i))
            for tag in input:
                
                if len(tag.name) > 25 or len(tag.name) < 3: continue
                
                fontSet = False
                for threshold in newThresholds[1:int(steps)+1]:
                    
                    if (100 * math.log(tag.count + 2)) <= threshold[0] and not fontSet:

                        size = float(threshold[1]) / 10.0 + (0.4)
                        
                        width = threshold[1] * 30
                        
                        results.append({"name" : abstract.utils.xssescape(tag.name), "weight" : threshold[1], "count" : tag.count, "size" : ("%.1f" % size), "width" : width})
                        
                        fontSet = True
            return results